# -*- coding:utf-8 -*-
"""
@author:  bingyl123@163.com
@version: 1.0.0
@file:    main.py
@time:    2023/2/23 19:58
"""
import random
import time
import threading
from flask import Flask, request, render_template
from faker import Faker
from log import create_logger
from r3 import r3
fake = Faker()


def simulated_generation_logs():
    """
    模拟生成后台日志，作为生产者
    实际生产环境中，各个业务逻辑产生日志
    :return:
    """
    def wrap():
        while True:
            sentence = fake.sentence()
            func = random.choice([r3.info, r3.warning, r3.error])        # 生成随机等级的日志
            func(sentence)
            time.sleep(1)
    thread = threading.Thread(target=wrap, name="simulated_generation_logs_thread", daemon=True)
    thread.start()


def create_app():
    app = Flask(__name__)
    # 创建日志
    create_logger()

    @app.get("/generate")
    def generate_logs():
        # 模拟生成日志
        simulated_generation_logs()
        return {"code": 200, "data": None, "msg": "ok"}

    @app.get("/message")
    def get_message():
        count = request.args.get("count", 50)
        data = r3.get(count)
        return {"code": 200, "data": data, "msg": "ok"}

    @app.get("/")
    def index_view():
        return render_template("index.html")
    return app


if __name__ == "__main__":
    app = create_app()
    app.run("127.0.0.1", port=5000, debug=True)
